<template>
  <Wrapper>
    <data-table
      :data="menus"
      :columns="columns"
      :border="false"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :load="(row, treeNode, resolve) => resolve(row.children)"
      row-key="name"
      lazy
    >
      <template #label="{ item }">
        <el-space>
          <icon
            v-if="item.meta.icon"
            :name="item.meta.icon"
            :type="item.meta?.iconType || ICON_TYPE.EL_ICON"
          />
          {{ item.label }}
        </el-space>
      </template>
      <template #type="{ item }">
        <el-tag
          effect="plain"
          :type="
            [SPECIAL_ROUTE_TYPE.LINK, SPECIAL_ROUTE_TYPE.IFRAME].includes(
              item.meta?.type,
            )
              ? 'warning'
              : 'success'
          "
          >{{ getMenuType(item.meta?.type) }}</el-tag
        >
      </template>
      <template #action="{ item }">
        <el-button type="primary" icon="View" link @click="open(item.meta)"
          >meta配置</el-button
        >
      </template>
    </data-table>

    <preview-meta-modal v-model="visible" :meta="modalData" />
  </Wrapper>
</template>

<script setup>
import { getDynamicMenus } from '@/router/helper/utils'
import { ICON_TYPE } from '@/const'
import { SPECIAL_ROUTE_TYPE } from '@/const/router'
import useModal from '@/hooks/useModal'
import DataTable from '@/components/table'
import PreviewMetaModal from './components/preview-meta-modal'

const { visible, modalData, open } = useModal()

const menus = ref([])
const columns = [
  { slot: 'label', label: '菜单名称', showOverflowTooltip: true },
  { slot: 'type', label: '菜单类型' },
  { prop: 'path', label: '路由path' },
  { prop: 'name', label: '路由name' },
  { prop: 'component', label: '组件路径' },
  { slot: 'action', label: '查看meta说明' },
].map((item) => ({ ...item, align: 'left' }))

onMounted(async () => {
  const res = await getDynamicMenus()
  menus.value = processMenus(res)
})

function processMenus(menuList) {
  return menuList.map((item) => {
    return {
      ...item,
      component: item.component || item.path,
      label: item.meta.title,
      hasChildren: item.children && item.children.length,
      children: item.children ? processMenus(item.children) : null,
    }
  })
}

function getMenuType(type) {
  const typeMap = {
    [SPECIAL_ROUTE_TYPE.LINK]: '外链',
    [SPECIAL_ROUTE_TYPE.IFRAME]: '内嵌',
  }
  return typeMap[type] || '菜单'
}
</script>
